package com.lmm.cg.zjgcg.pages.choosephoto;


import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.OrientationEventListener;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.lmm.cg.zjgcg.R;
import com.lmm.cg.zjgcg.actions.PhotoAction;
import com.lmm.cg.zjgcg.camera.CameraInterface;
import com.lmm.cg.zjgcg.camera.CameraParaUtil;
import com.lmm.cg.zjgcg.camera.CameraPreview;
import com.lmm.cg.zjgcg.camera.utils.BitmapUtils;
import com.lmm.cg.zjgcg.camera.utils.DeleteFileUtil;
import com.lmm.cg.zjgcg.camera.utils.DialogUtil;
import com.lmm.cg.zjgcg.camera.utils.XPermissionUtils;
import com.lmm.cg.zjgcg.config.ConfigValue;
import com.lmm.cg.zjgcg.pages.AppBaseActivity;
import com.lmm.cg.zjgcg.pages.ReactNativePresent;
import com.lmm.cg.zjgcg.task.TaskCallBack;
import com.lmm.cg.zjgcg.utils.UploadFileUtil;
import com.lmm.dresswisdom.lmmframe.retrofit.AppClient;
import com.lmm.dresswisdom.lmmframe.util.LogUtils;
import com.lmm.dresswisdom.lmmframe.util.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

@Route(path = "/page/takechoose")
public class TakeChoosePhotoActivity3 extends AppBaseActivity implements View.OnClickListener, CameraInterface.CameraListener {

    private final String TAG = "SydCamera";
    private final int PERMISSION_REQUEST_CODE_CAMERA = 0x02;
    private final int PERMISSION_REQUEST_CODE_STORAGE = 0x03;
    private FrameLayout preview;
    private CameraPreview mSurfaceView;
    private ImageView img_take_picture;
    private ImageView img_switch_camera;
    private ImageView img_exit;
    private OrientationEventListener mOrientationListener;
    private int cameraOrientation = 0;
    private int picQuality;
    private int picWidth;
    private int previewWidth;
    private int pictureSize;

    private boolean isUpload = false;

    private int uploadCount = 99; //上传计数

    ImageButton btnCancel;//取消
    ImageButton btnTakePhoto;//拍照
    ImageButton btnComplete;//完成
    Switch switchLight;//闪光灯
    RecyclerView recyclerView;//图片列表
    PhotoSimpleAdapter photpAdapter;

    @Autowired(name = "refreshToken")
    public String refreshToken = "";
    @Autowired(name = "accessToken")
    public String accessToken = "";
    @Autowired(name = "type")
    public String uploadType = "";
    @Autowired(name = "guid")
    public String recordGuid = "";
    @Autowired(name = "photos")
    public ArrayList<String> oldPhotos = new ArrayList<>();

    LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    private List<PhotoModal> fileLst = new ArrayList<>();
    ReactNativePresent mPresent;

    PhotoAction photoAction;

    UploadFileUtil uploadUtil;

    private final String rootPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "cg" + File.separator;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ARouter.getInstance().inject(this);
        setContentView(R.layout.activity_choosephoto);

        picQuality = CameraParaUtil.defaultPicQuality;
        picWidth = CameraParaUtil.defaultPicWidth;
        previewWidth = CameraParaUtil.defaultPreviewWidth;

        initView();
        checkCameraPermission();
        checkSdPermission();

        photoAction = AppClient.getRetrofit(ConfigValue.API_Url).create(PhotoAction.class);


        if (!new File(rootPath).exists()) {
            new File(rootPath).mkdirs();
        }

    }


    private void setOldPhotos() {
        PhotoModal pm = null;
        if (oldPhotos.size() > 0) {
            for (String item : oldPhotos) {
                pm = new PhotoModal();
                pm.setFilePath("");
                pm.setMfile(null);
                pm.setNetAddress(item);
                pm.setUpload(true);
                fileLst.add(pm);
            }
        }


        if (uploadType.toLowerCase().equals("cpgl")) {
            uploadCount = 3 - fileLst.size();
        }
    }

    private void initView() {
        preview = (FrameLayout) findViewById(R.id.camera_preview);
        layoutManager.setOrientation(OrientationHelper.HORIZONTAL);
        btnCancel = (ImageButton) findViewById(R.id.cancel);
        btnComplete = (ImageButton) findViewById(R.id.info);
        btnTakePhoto = (ImageButton) findViewById(R.id.picture);
        switchLight = (Switch) findViewById(R.id.switch_light);

        recyclerView = (RecyclerView) findViewById(R.id.recy_photo);
        recyclerView.setLayoutManager(layoutManager);

        btnComplete.setOnClickListener(this);
        btnTakePhoto.setOnClickListener(this);
        btnCancel.setOnClickListener(this);

        switchLight.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    Camera.Parameters parameters = CameraInterface.getInstance().getCamera().getParameters();
                    parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                    CameraInterface.getInstance().getCamera().setParameters(parameters);
                } else {
                    Camera.Parameters parameters = CameraInterface.getInstance().getCamera().getParameters();
                    parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
                    CameraInterface.getInstance().getCamera().setParameters(parameters);
                }
            }
        });

        setOldPhotos();
        photpAdapter = new PhotoSimpleAdapter(fileLst);
        photpAdapter.setContext(this);
        photpAdapter.setDelInterface(new PhotoDelInterface() {
            @Override
            public void delAction(int index) {
                delIndex = index;
                if (fileLst.get(index).getNetAddress().length() > 0) {
                    delNetPhoto(fileLst.get(index).getNetAddress());
                } else {
                    fileLst.remove(index);
                    photpAdapter.notifyDataSetChanged();
                }
            }
        });
        recyclerView.setAdapter(photpAdapter);

        mPresent = new ReactNativePresent();
        //监听手机旋转角度
        mOrientationListener = new OrientationEventListener(this) {
            @Override
            public void onOrientationChanged(int orientation) {
                cameraOrientation = orientation;
            }
        };
    }


    int delIndex = 0;

    private void delNetPhoto(String filePath) {

        if (uploadUtil == null) {
            uploadUtil = new UploadFileUtil();
        }

        uploadUtil.deleteNetFile(filePath, uploadType, refreshToken, accessToken, new TaskCallBack<String>() {
            @Override
            public void onSuccess(String s) {
                fileLst.remove(delIndex);
                btnTakePhoto.setEnabled(true);
                photpAdapter.notifyDataSetChanged();
                uploadCount++;
            }

            @Override
            public void onFail(String s) {
                LogUtils.write(s);
            }

            @Override
            public void onFinish() {

            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v == btnTakePhoto) {
            btnTakePhoto.setEnabled(false);
            showDefaultDialog();
            if (uploadType.toLowerCase().equals("cpgl")) {
                if (fileLst.size() < 3) {
                    CameraInterface.getInstance().takePicture();
                } else {
                    hideDefaultDialog();
                    btnTakePhoto.setEnabled(true);
                    ToastUtils.showToastShort("抄牌管理只能选3张照片");
                    return;
                }
            } else {
                CameraInterface.getInstance().takePicture();
            }
        } else if (v == btnCancel) {
            setResult(RESULT_CANCELED);
            finish();
        } else if (v == btnComplete) {
            if (isUpload) {
                return;
            }

            if (uploadType.toLowerCase().equals("cpgl")) {
                if (fileLst.size() != 3) {
                    Toast.makeText(TakeChoosePhotoActivity3.this, "请选择3张照片上传", Toast.LENGTH_SHORT).show();
                    return;
                }
            }

            showDefaultDialog();
            uploadAllFile();

        }
    }

    private void deleteItem(String filepath) {
        File file = new File(filepath);
        if (file.exists() && file.length() > 0) {
            file.delete();
        }
    }

    private void uploadAllFile() {
        isUpload = true;
        btnTakePhoto.setEnabled(false);
        for (PhotoModal item : fileLst) {
            if (!item.isUpload()) {
                if (uploadCount > 0) {
                    uploadCount--;
                    Log.i(TAG, "uploadCount:" + uploadCount);
                    uploadItem(item);
                    return;
                }
            }
        }

//        for (PhotoModal item : fileLst) {
//            if (item.isUpload()) {
//                deleteItem(item.getFilePath());
//            }
//        }

        // 删除文件夹
//        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
//                Environment.DIRECTORY_PICTURES), "sydPhoto");
//        deleteDirectory(mediaStorageDir.getPath());


        hideDefaultDialog();

        // 全部上传完成
        // 回掉
        Intent mintent = new Intent();
        String imgUrls = "";
        String ajbh = "";
        for (PhotoModal item : fileLst) {
            imgUrls += item.getNetAddress() + ";";
            ajbh = item.getAjbh();
        }
        mintent.putExtra("imgs", imgUrls);
        mintent.putExtra("ajbh", ajbh);
        Log.i(TAG, imgUrls);
        setResult(RESULT_OK, mintent);
        finish();
    }


    /**
     * 删除目录及目录下的文件
     *
     * @param dir 要删除的目录的文件路径
     * @return 目录删除成功返回true，否则返回false
     */
    public static boolean deleteDirectory(String dir) {
        // 如果dir不以文件分隔符结尾，自动添加文件分隔符
        if (!dir.endsWith(File.separator))
            dir = dir + File.separator;
        File dirFile = new File(dir);
        // 如果dir对应的文件不存在，或者不是一个目录，则退出
        if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
            System.out.println("删除目录失败：" + dir + "不存在！");
            return false;
        }
        boolean flag = true;
        // 删除文件夹中的所有文件包括子目录
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            // 删除子文件
            if (files[i].isFile()) {
                try {
                    flag = DeleteFileUtil.deleteFile(files[i].getAbsolutePath());
                } catch (Exception e) {

                }
                if (!flag)
                    break;
            }
            // 删除子目录
            else if (files[i].isDirectory()) {
                flag = DeleteFileUtil.deleteDirectory(files[i]
                        .getAbsolutePath());
                if (!flag)
                    break;
            }
        }
        if (!flag) {
            System.out.println("删除目录失败！");
            return false;
        }
        // 删除当前目录
        if (dirFile.delete()) {
            System.out.println("删除目录" + dir + "成功！");
            return true;
        } else {
            return false;
        }
    }


    private void scanFileAsync(String filePath) {
        Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        scanIntent.setData(Uri.fromFile(new File(filePath)));
        sendBroadcast(scanIntent);
    }

    /**
     * 单个文件上传方法
     *
     * @param image
     */
    private void uploadItem(final PhotoModal image) {
        if (uploadType.equals("jycxPj") || uploadType.equals("jycxZp")) {
            if (uploadUtil == null) {
                uploadUtil = new UploadFileUtil();
            }
            uploadUtil.uploadJXAJ(recordGuid, uploadType, new File(image.getFilePath()), refreshToken, accessToken, new TaskCallBack<String>() {
                @Override
                public void onSuccess(String result) {
                    Log.i("Eric", result);
                    image.setUpload(true);

                    try {
                        //String转JSONObject
                        JSONObject jsonObject = new JSONObject(result);
                        JSONObject jsonData = null;
                        String picName = "";
                        if (jsonObject.getInt("result") == 200) {
                            jsonData = jsonObject.getJSONObject("data");
                            if (jsonData.has("picName")) {
                                picName = jsonData.getString("picName");
                                //取数据
                                String netaddress = "";
                                if (uploadType.equals("jycxPj")) {
                                    netaddress = ConfigValue.IMG_HEAD_Url + "JYAJ" + File.separator + recordGuid + File.separator + "01" + File.separator + picName;
                                } else {
                                    netaddress = ConfigValue.IMG_HEAD_Url + "JYAJ" + File.separator + recordGuid + File.separator + "02" + File.separator + picName;
                                }
                                image.setNetAddress(netaddress);
                                uploadAllFile();
                            }
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();

                    }

                }

                @Override
                public void onFail(String s) {
                    Log.i("Eric", s);
                    hideDefaultDialog();
                    image.setUpload(false);
                    ToastUtils.showToastShort("图片上传出错");
                }

                @Override
                public void onFinish() {
                    hideDefaultDialog();
                    Log.i("Eric", "onFinish");
                }
            });

        } else if (uploadType.equals("ybaj_zj") || uploadType.equals("ybaj_xc")) {
            // 一般案件
            if (uploadUtil == null) {
                uploadUtil = new UploadFileUtil();
            }
            uploadUtil.uploadYBAJ(recordGuid, new File(image.getFilePath()), uploadType, refreshToken, accessToken, new TaskCallBack<String>() {
                @Override
                public void onSuccess(String result) {
                    Log.i("Eric", result);
                    image.setUpload(true);
                    try {
                        //String转JSONObject
                        JSONObject jsonObject = new JSONObject(result);
                        JSONObject jsonData = null;
                        String picName = "";
                        String ajbh = "";
                        if (jsonObject.getInt("result") == 200) {
                            jsonData = jsonObject.getJSONObject("data");
                            if (jsonData.has("picName")) {
                                picName = jsonData.getString("picName");

                                if (TextUtils.isEmpty(recordGuid)) {
                                    recordGuid = jsonData.getString("ajGuid");
                                }

                                if (jsonData.has("sl_ajbh")) {
                                    ajbh = jsonData.getString("sl_ajbh");
                                }

                                if (!TextUtils.isEmpty(ajbh)) {
                                    image.setAjbh(ajbh);
                                }

                                //取数据
                                String netaddress = "";
                                if (uploadType.equals("ybaj_zj")) {
                                    netaddress = ConfigValue.IMG_HEAD_Url + "YBAJ" + File.separator + recordGuid + File.separator + "ajzj" + File.separator + picName;
                                } else {
                                    netaddress = ConfigValue.IMG_HEAD_Url + "YBAJ" + File.separator + recordGuid + File.separator + "xcczws" + File.separator + picName;
                                }
                                image.setNetAddress(netaddress);
                                uploadAllFile();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();

                    }

                }

                @Override
                public void onFail(String s) {
                    Log.i("Eric", s);
                    hideDefaultDialog();
                    image.setUpload(false);
                    ToastUtils.showToastShort("图片上传出错");
                }

                @Override
                public void onFinish() {
                    hideDefaultDialog();
                    Log.i("Eric", "onFinish");
                }
            });


        } else if (uploadType.equals("ssj_fk")) {
            // 双随机反馈
            if (uploadUtil == null) {
                uploadUtil = new UploadFileUtil();
            }
            uploadUtil.uploadSSJFK(recordGuid, new File(image.getFilePath()), refreshToken, accessToken, new TaskCallBack<String>() {
                @Override
                public void onSuccess(String result) {
                    Log.i("Eric", result);
                    image.setUpload(true);
                    try {
                        //String转JSONObject
                        JSONObject jsonObject = new JSONObject(result);
                        JSONObject jsonData = null;
                        String picName = "";
                        if (jsonObject.getInt("result") == 200) {
                            jsonData = jsonObject.getJSONObject("data");
                            if (jsonData.has("picName")) {
                                picName = jsonData.getString("picName");


                                //取数据
                                String netaddress = "";
                                netaddress = ConfigValue.IMG_HEAD_Url + "FK" + File.separator + recordGuid + File.separator + picName;
                                image.setNetAddress(netaddress);
                                uploadAllFile();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();

                    }

                }

                @Override
                public void onFail(String s) {
                    Log.i("Eric", s);
                    hideDefaultDialog();
                    image.setUpload(false);
                    ToastUtils.showToastShort("图片上传出错");
                }

                @Override
                public void onFinish() {
                    hideDefaultDialog();
                    Log.i("Eric", "onFinish");
                }
            });
        } else if (uploadType.equals("ssj_hf")) {
            // 双随机反馈
            if (uploadUtil == null) {
                uploadUtil = new UploadFileUtil();
            }
            uploadUtil.uploadSSJHF(recordGuid, new File(image.getFilePath()), refreshToken, accessToken, new TaskCallBack<String>() {
                @Override
                public void onSuccess(String result) {
                    Log.i("Eric", result);
                    image.setUpload(true);
                    try {
                        //String转JSONObject
                        JSONObject jsonObject = new JSONObject(result);
                        JSONObject jsonData = null;
                        String picName = "";
                        if (jsonObject.getInt("result") == 200) {
                            jsonData = jsonObject.getJSONObject("data");
                            if (jsonData.has("picName")) {
                                picName = jsonData.getString("picName");


                                //取数据
                                String netaddress = "";
                                netaddress = ConfigValue.IMG_HEAD_Url + "HF" + File.separator + recordGuid + File.separator + picName;
                                image.setNetAddress(netaddress);
                                uploadAllFile();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();

                    }

                }

                @Override
                public void onFail(String s) {
                    Log.i("Eric", s);
                    hideDefaultDialog();
                    image.setUpload(false);
                    ToastUtils.showToastShort("图片上传出错");
                }

                @Override
                public void onFinish() {
                    hideDefaultDialog();
                    Log.i("Eric", "onFinish");
                }
            });
        } else {
            Log.i("Eric", "开始上传：" + image.getFilePath());

            if (uploadUtil == null) {
                uploadUtil = new UploadFileUtil();
            }

            uploadUtil.uploadWT(recordGuid, new File(image.getFilePath()), refreshToken, accessToken, new TaskCallBack<String>() {
                @Override
                public void onSuccess(String result) {
                    Log.i("Eric", result);
                    image.setUpload(true);
                    try {
                        //String转JSONObject
                        JSONObject jsonObject = new JSONObject(result);
                        JSONObject jsonData = null;
                        String picName = "";
                        if (jsonObject.getInt("result") == 200) {
                            jsonData = jsonObject.getJSONObject("data");
                            if (jsonData.has("picName")) {
                                picName = jsonData.getString("picName");
                                //取数据
                                String netaddress = ConfigValue.IMG_HEAD_Url + "WT" + File.separator + recordGuid + File.separator + picName;
                                image.setNetAddress(netaddress);
                                uploadAllFile();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();

                    }

                }

                @Override
                public void onFail(String s) {
                    Log.i("Eric", s);
                    hideDefaultDialog();
                    image.setUpload(false);
                    ToastUtils.showToastShort("图片上传出错");
                }

                @Override
                public void onFinish() {
                    hideDefaultDialog();
                    Log.i("Eric", "onFinish");
                }
            });
        }
    }

    private void initCameraView() {
        CameraInterface.getInstance().setMinPreViewWidth(previewWidth);
        CameraInterface.getInstance().setMinPicWidth(picWidth);
        CameraInterface.getInstance().setCameraListener(this);
        mSurfaceView = new CameraPreview(this);
        mSurfaceView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
//                CameraInterface.getInstance().focusOnTouch((int) event.getX(), (int) event.getY(), preview);
                return false;
            }
        });
        preview.addView(mSurfaceView);
    }

    private void checkCameraPermission() {
        XPermissionUtils.requestPermissions(this, PERMISSION_REQUEST_CODE_CAMERA, new String[]{Manifest.permission.CAMERA},
                new XPermissionUtils.OnPermissionListener() {
                    @Override
                    public void onPermissionGranted() {
                        Log.i(TAG, "checkCameraPermission onPermissionGranted");
                        if (CameraInterface.getInstance().getCamera() == null) {
                            Log.e(TAG, "checkCameraPermission getCamera() == null");
                            DialogUtil.showPermissionDeniedDialog(TakeChoosePhotoActivity3.this, "相机");
                        } else {
                            initCameraView();
                        }
                    }

                    @Override
                    public void onPermissionDenied(final String[] deniedPermissions, boolean alwaysDenied) {
                        Toast.makeText(TakeChoosePhotoActivity3.this, "获取相机权限失败", Toast.LENGTH_SHORT).show();
                        if (alwaysDenied) { // 拒绝后不再询问 -> 提示跳转到设置
                            DialogUtil.showPermissionDeniedDialog(TakeChoosePhotoActivity3.this, "相机");
                        } else {    // 拒绝 -> 提示此公告的意义，并可再次尝试获取权限
                            DialogUtil.showPermissionRemindDiaog(TakeChoosePhotoActivity3.this, "相机", deniedPermissions, PERMISSION_REQUEST_CODE_CAMERA);
                        }
                    }
                });
    }

    private void checkSdPermission() {
        XPermissionUtils.requestPermissions(this, PERMISSION_REQUEST_CODE_STORAGE, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                new XPermissionUtils.OnPermissionListener() {
                    @Override
                    public void onPermissionGranted() {
                        Log.i(TAG, "checkSdPermission onPermissionGranted");
                    }

                    @Override
                    public void onPermissionDenied(final String[] deniedPermissions, boolean alwaysDenied) {
                        Log.i(TAG, "checkSdPermission onPermissionDenied");
                        if (alwaysDenied) { // 拒绝后不再询问 -> 提示跳转到设置
                            DialogUtil.showPermissionDeniedDialog(TakeChoosePhotoActivity3.this, "文件存储");
                        } else {    // 拒绝 -> 提示此公告的意义，并可再次尝试获取权限
                            DialogUtil.showPermissionRemindDiaog(TakeChoosePhotoActivity3.this, "文件存储", deniedPermissions, PERMISSION_REQUEST_CODE_CAMERA);
                        }
                    }
                });
    }

//    @Override
//    public void onTakePictureSuccess(File pictureFile) {
//        BitmapFactory.Options options = new BitmapFactory.Options();
//        options.inPreferredConfig = Bitmap.Config.RGB_565;
//        Bitmap bitmap = BitmapUtils.rotateBitmap(BitmapFactory.decodeFile(pictureFile.getPath(), options), CameraInterface.getInstance().getmCameraId(), cameraOrientation);
//        if (pictureSize > 0) {
//            bitmap = BitmapUtils.bitmapCompress(bitmap, 120);
//        }
//        BitmapUtils.saveBitmapToSd(bitmap, pictureFile.getPath(), picQuality);
//
//        String path = pictureFile.getPath();
//        PhotoModal pm = new PhotoModal();
//        pm.setFilePath(path);
//        pm.setUpload(false);
//        fileLst.add(pm);
//        refreshImgs();
//
//        btnTakePhoto.setEnabled(true);
//
//        hideDefaultDialog();
//    }

    @Override
    public void onTakePictureSuccess(File pictureFile) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        Bitmap bitmap = BitmapUtils.rotateBitmap(BitmapFactory.decodeFile(pictureFile.getPath(), options), CameraInterface.getInstance().getmCameraId(), cameraOrientation);
//        Bitmap bitmap = BitmapUtils.rotateBitmap(BitmapFactory.decodeFile(pictureFile.getPath(), options), 45);
//        Bitmap waterBitmap = WaterMaskUtils.drawTextToRightBottom(this, bitmap, "waterMaskTest123", 16, Color.RED, 0, 0);
//        Bitmap smallBitmap = BitmapUtils.bitmapCompress(bitmap, 120);
        if (pictureSize > 0) {
            bitmap = BitmapUtils.bitmapCompress(bitmap, 120);
        }
//        bitmap = BitmapUtils.compressToSizeByQuality(bitmap, 120);
//        Log.i(TAG, "onTakePictureSuccess bitmap.getWidth: " + bitmap.getWidth() + ", bitmap.getHeight():" + bitmap.getHeight());
//        Log.i(TAG, "onTakePictureSuccess picQuality: " + picQuality + ", bitmap.getByteCount():" + bitmap.getByteCount());
//        Log.d(TAG, "onTakePictureSuccess picQuality: " + picQuality + ", smallBitmap.getByteCount():" + smallBitmap.getByteCount());
        BitmapUtils.saveBitmapToSd(bitmap, pictureFile.getPath(), picQuality);

        //更新本地相册
        Intent localIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(pictureFile));
        sendBroadcast(localIntent);

        CompressImg(pictureFile, rootPath);

//        PhotoModal pm = new PhotoModal();
//        pm.setFilePath(pictureFile.getPath());
//        pm.setBigFilePath(pictureFile.getAbsolutePath());
//        pm.setUpload(false);
//
//        fileLst.add(pm);
//        btnTakePhoto.setEnabled(true);
//        refreshImgs();

        btnTakePhoto.setEnabled(true);
        hideDefaultDialog();
    }


    /**
     * 压缩图片
     */
    private void CompressImg(final File loadFile, String tempFilePath) {
        Luban.with(this)
                .load(loadFile)
                .ignoreBy(100)
                .setTargetDir(tempFilePath)
                .filter(new CompressionPredicate() {
                    @Override
                    public boolean apply(String path) {
                        return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                    }
                })
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        LogUtils.write("start");
                    }

                    @Override
                    public void onSuccess(File file) {
                        String path = file.getPath();
                        PhotoModal pm = new PhotoModal();
                        pm.setFilePath(path);
                        pm.setBigFilePath(loadFile.getAbsolutePath());
                        pm.setUpload(false);

                        fileLst.add(pm);
                        btnTakePhoto.setEnabled(true);
                        refreshImgs();
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtils.write(e.getMessage());
                    }
                }).launch();
    }

    private void refreshImgs() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                photpAdapter.notifyDataSetChanged();
            }
        });
    }


    @Override
    public void onTakePictureFail(byte[] data) {
//        canUpload = true;
        Log.e(TAG, "拍照失败，请检查权限设置!"); //三星A8出现无法创建文件夹的提示，重启恢复正常
        CameraParaUtil.pictureBitmap = BitmapUtils.rotateBitmap(BitmapUtils.Bytes2Bitmap(data), CameraInterface.getInstance().getmCameraId(), cameraOrientation);
        Intent intent = new Intent();
        setResult(CameraParaUtil.REQUEST_CODE_FROM_CAMERA_FAIL, intent);
        finish();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        XPermissionUtils.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mOrientationListener.enable();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mOrientationListener != null)
            mOrientationListener.disable();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        for (PhotoModal item : fileLst) {
            deleteItem(item.getFilePath());
        }
        // 删除文件夹
        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES), "sydPhoto");
        deleteDirectory(mediaStorageDir.getPath());
    }
}
